<template>
  <div class="system-chart task-mt12">
    <div class="chart-header task-flex task-ai">
      <div class="task-span1 task-flex task-ai">
        <div class="chart-icon task-bjc2 task-mr12"><i class="iconfont icon-signal-fill"></i></div>
        <el-tooltip placement="top">
          <div slot="content">{{ $t('report.productChart.title1') }}</div>
          <i class="iconfont icon-question task-icon"></i>
        </el-tooltip>
      </div>
      <div class="task-ml12 task-pointer">
        <el-dropdown @command="handleClick">
          <div>
            <i class="iconfont icon-paixu1"></i>
            {{sort}}
            <i class="iconfont icon-triangle-down"></i>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="$t('report.productChart.defaultSort')">{{ $t('report.productChart.defaultSort') }}</el-dropdown-item>
            <el-dropdown-item :command="$t('report.productChart.priceSort1')">{{ $t('report.productChart.priceSort1') }}</el-dropdown-item>
            <el-dropdown-item :command="$t('report.productChart.priceSort2')">{{ $t('report.productChart.priceSort2') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="task-flex task-pointer">
        <div class="task-ml12" @click="downLoadImage">
          <i class="iconfont icon-cloud-download"></i>
          {{ $t('product.component.qrcodeDialog.btn2') }}
        </div>
      </div>
    </div>
    <!-- 折线图 -->
    <div class="chart-content">
      <div id="chart" v-if="taskCharts.length"></div>
      <stats-chart-empty v-if="taskCharts.length==0 && !loading">{{$t('common.base.tip.noData')}}</stats-chart-empty>
    </div>
    <!-- 表格 -->
    <div class="table task-mt12" v-show="tableNames.length">
      <div class="chart-header task-flex task-ai task-pointer">
        <div class="task-span1"></div>
        <div class="task-flex">
          <div @click="taskExport(false)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.export') }}
          </div>
          <div class="task-ml12" @click="taskExport(true)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.exportAll') }}
          </div>
          <div class="task-ml12" @click="tableNames = []">
            {{ $t('common.base.collapse') }}
            <i class="iconfont icon-triangle-down"></i>
          </div>
        </div>
      </div> 
      <!-- table -->
      <el-table
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in product"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            <!-- 工单编号 -->
            <template v-if="item.fieldName === 'taskNo'">
              <a
                href=""
                class="view-detail-btn task-list-numbering"
                @click.stop.prevent="
                  openTaskTab(scope.row.id, scope.row[item.fieldName])
                "
              >
                {{scope.row[item.fieldName]}}
              </a>
            </template>

            <template v-else-if="item.fieldName === 'executorUserName'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executorUserName }}
              </template>
            </template>

            <!-- 产品 -->
            <template v-else-if="item.fieldName === 'productName'">
              {{scope.row[item.fieldName] && scope.row[item.fieldName].join(',')}}
            </template>
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="spare-parts-foot task-flex task-ai report-spare-parts-foot">
        <span class="task-c90">{{$t('report.system.total',{num:pagination.total})}}</span>
        <el-pagination
          class="comment-list-table-footer-pagination task-span1"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="pageSize"
          :total="pagination.total"
          :current-page="pageNum"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
      
      </div>   
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';

import {PRODUCT} from '../../common/tableModel'
import { formatDate } from 'pub-bbx-utils';
import qs from 'qs';
import { checkButtonDisplayed } from '@src/util/dom';
// API
import * as ReportApi from '@src/api/ReportApi.ts';
import { safeNewDate } from '@src/util/time';

/* component */
import StatsChartEmpty from '@src/modules/report/common/StatsChartEmpty.vue';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'
import _ from 'lodash';
export default {
  name: 'product-chart',
  components: {
    [StatsChartEmpty.name]: StatsChartEmpty
  },
  props: {
    taskCharts: {
      type: Array,
    }, // 图表数据
    params: {
      type: Object
    }, // table参数
    loading: {
      type: Boolean
    },
    reportType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      defaultTableData,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      product:PRODUCT,
      sort: t('report.productChart.defaultSort'),
      tableNames: [],
      pageSize: 10,
      pageNum: 1,
      productType: '',
      pagination: {}
    }
  },
  watch: {
    taskCharts(v) {
      this.histogram(v)
    }
  },
  methods: {
    // 排序
    handleClick(v) {
      this.sort = v
      let sorts
      switch (v) {
      case t('report.productChart.priceSort1'):
        sorts = [{'property':'total', 'direction':'DESC'}]
        break;
      case t('report.productChart.priceSort2'):
        sorts = [{'property':'total', 'direction':'ASC'}]
        break;      
      default:
        sorts = ''
        break;
      }
      this.$emit('taskTable', {
        sorts,
      })
    },
    // 转成图片并下载
    convertCanvasToImage() {
      const canvas = document.querySelector('#chart div canvas')
      const img = canvas.toDataURL('image/png');
      const oA = document.createElement('a');
      oA.download = t('report.system.title1');// 设置下载的文件名，默认是'下载'
      oA.href = img;
      document.body.appendChild(oA);
      oA.click();
      oA.remove();
    },
    downLoadImage() {
			this.convertCanvasToImage()
			// 下载图片埋点
      this.reportType && this.$track.commonFn.chartTrack(this.reportType, 'DOWNLOAD_REPORT_IMAGE', this.$track)
		},
    // 柱状图
    histogram(data) {
      this.$nextTick(() => {
        if (!document.getElementById('chart')) return
        const myChart = echarts.init(document.getElementById('chart'))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            data: data.map(item => {return item.productTypeName})
          },
          yAxis: {
            type: 'value',
          },
          dataZoom: [
            {
              show: true,
              start: 0,
              end: 40
            }
          ],
          series: [{
            data: data.map(item => {return item.count}),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            },
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };

        this.tableNames = []
        if(!data.length) return

        myChart.setOption(option, true);

        this.pageSize = 10
        this.pageNum = 1
        myChart.on('click', e => {
          this.pageSize = 10
          this.pageNum = 1
          this.repairedPage(e)
        })
        window.addEventListener('resize', _.debounce(function(){
          myChart.resize();
        }, 400))
      })
    },
    // 产品报修率统计-工单-分页数据
    async repairedPage({name}) {
      this.productType = name
      const {pageSize, pageNum} = this
      const params = {...this.params, pageSize, pageNum, productType: name}
      const {list, total} = await ReportApi.repairedPage(params)
      this.tableNames = list.map(item => {
        item.productType = name
        item.planDateTime = formatDate(safeNewDate(item.planDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss')
        return item
      })
      this.pagination = {
        total,
      };
    },
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    // 导出
    taskExport(isExportAll) {
      const {productType} = this
      const params = {...this.params, productType: isExportAll ? '' : productType, isExportAll}
      window.location.href = `/api/report/outside/stats/product/repaired/export?${qs.stringify(params)}`

      this.$emit('export-track', isExportAll)
    },
    /* 分页条数切换 */
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value;
      this.repairedPage({name: this.productType});
    },
    /* 分页页数切换 */
    handlePageChange(value) {
      this.pageNum = value;
      this.repairedPage({name: this.productType});
    },
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
  },
}
</script>
<style lang="scss" scoped>
@import '../system.scss';

.system-chart-tab {
    width: 90px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    background: #fff;
    border: 1px solid rgba(217, 217, 217, 1);
    &:first-child{
        border-radius: 4px 0px 0px 4px;
        border-right: 0;
    }
    &:last-child{ 
        border-radius: 0px 4px 4px 0px;
        border-left: 0;
    }
}
.active {
    color: #fff;
    background-color: $color-primary;
    border-color: $color-primary;
}
</style>